package com.alm.token.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import baibeiwallet.event.CreateWalletEvent;
import baibeiwallet.event.RefreshMeEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.BaseDialogBean;
import com.alm.token.ui.data.bean.GoogleAuthKeyData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UpdateData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.fragmentDialog.ToBindDialogFragment;
import com.alm.token.ui.fragmentDialog.ToSetPayPswDialogFragment;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.MainView;
import com.alm.token.ui.viewpagefragment.ApplicationPageFrag;
import com.alm.token.ui.viewpagefragment.FortunePageFrag;
import com.alm.token.ui.viewpagefragment.HangQingPageFrag;
import com.alm.token.ui.viewpagefragment.FindMorePageFrag;
import com.alm.token.ui.viewpagefragment.MePageFrag;
import com.alm.token.ui.viewpagefragment.WalletPageFrag;
import com.alm.token.utils.ADBInstallApk;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.SpUtil;
import com.alm.token.widget.NoScrollViewPager;
import com.yinglan.alphatabs.AlphaTabsIndicator;
import com.yinglan.alphatabs.OnTabChangedListner;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static com.alm.token.ui.activity.BindEmaiActivity.BINDMAI_bind;
import static com.alm.token.ui.activity.BindEmaiActivity.BINDMAI_up;
import static com.alm.token.ui.activity.BindGoogleCodeActivity.BINDGOOGLECODE_BINd;
import static com.alm.token.ui.activity.BindGoogleCodeActivity.BINDGOOGLECODE_UNBINd;
import static com.alm.token.ui.activity.MnemonicActivity.INTENT_Mnemonic_INTO_CODE;
import static com.alm.token.ui.fragmentDialog.ToBindDialogFragment.BINDTYPE_GOOGLECODE;
import static com.alm.token.ui.fragmentDialog.ToBindDialogFragment.BINDTYPE_MAIL;
import static com.alm.token.ui.fragmentDialog.ToBindDialogFragment.BINDTYPE_MONIC;

public class MainActivity extends BaseActivity implements MainView<UpdateData>,
         MaterialDialog.SingleButtonCallback, MePageFrag.MeFragLisenter {

    @BindView(R.id.alphaIndicator)
    AlphaTabsIndicator alphaIndicator;
    @BindView(R.id.view_page)
    NoScrollViewPager viewPage;
    private MainViewPageAdapter adapter;
    private MaterialDialog progressDialog;
    private int mLocalVersionCode;
    private String updateApkUrl, apkname;
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder builder;
    int progressm1 = 0;
    MainActyLisenter mainActyLisenter;
    MainActyHangQingLisenter mainActyHangQingLisenter, mainActyFanXianLisenter;


    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
        initViewPage();
        initIndicator();
    }


    @Override
    protected void loadData() {
        mLocalVersionCode = getVersionCode();
        preenter.getUpdateData("1");//1 安卓
//        jumpToLoginAct(666);
    }

    @Override
    public void onClick(View v) {

    }

    private void initViewPage() {

        adapter = new MainViewPageAdapter(getSupportFragmentManager(), this);
        mainActyLisenter = adapter.getMainActyLisenter();
        mainActyHangQingLisenter = adapter.getMainActyHangQingLisenter();
        mainActyFanXianLisenter = adapter.getMainActyFaXianLisenter();
        viewPage.setAdapter(adapter);
        viewPage.setOffscreenPageLimit(4);
        viewPage.addOnPageChangeListener(adapter);
    }

    int tabId;

    private void initIndicator() {
        alphaIndicator.setViewPager(viewPage);
        alphaIndicator.setOnTabChangedListner(new OnTabChangedListner() {
            @Override
            public void onTabSelected(int tabNum) {
                tabId = tabNum;
                if (tabId == 4) {
                    EventBus.getDefault().post(new RefreshMeEvent(0));
                }
//                showToast(tabId+"");
//                if (tabNum == 2) {
//                    startActivity(QuantitativeOrderActivity.class);
//                }
            }
        });
    }

    UpdateData.DataBean dataBean;

    @Override
    public void getData(UpdateData updateData) {
        if (updateData.getStatus() == 0) {//请求成功
            dataBean = updateData.getData();
            updateApkUrl = dataBean.getDownload();
            MyApp.setUpdateApkUrl(updateApkUrl);
//            updateApkUrl = "http://gyxz.ukdj3d.cn/a3/rj_wn1/360daikuandaohang.apk";//模拟下载安装地址
            apkname = dataBean.getApkname() + dataBean.getVersioncode();
            LogUtil.e("apkname=" + dataBean.getApkname() + " url=" + updateApkUrl + " versioncode=" + dataBean.getVersioncode());
//            showToast("apkname=" + dataBean.getApkname() + " url=" + updateApkUrl + " versioncode=" + dataBean.getVersioncode());
            if (Integer.parseInt(dataBean.getVersioncode()) > mLocalVersionCode) {
                MyApp.needUpdaate = true;
//                if (SpUtil.getString(this, ConStant.UPDATEPATH, "").isEmpty()
//                        || (!SpUtil.getString(this, ConStant.UPDATEPATH, "").isEmpty()
//                        && SpUtil.getString(this, ConStant.UPDATEPATH, "").indexOf(apkname) == -1)) {
//                    showUpdateAlertDialog(this, "版本更新",
//                            !TextUtils.isEmpty(dataBean.getVersiondes())?dataBean.getVersiondes():"有新版本更新啦!",
//                            "同意", "取消", this);
//                } else {
//                    LogUtil.d("apkpath"+ SpUtil.getString(this, ConStant.UPDATEPATH, ""));
//                    onDownloadSuccess(SpUtil.getString(this, ConStant.UPDATEPATH, ""));
//                }


                //下载更新
//                if (versionBean.getResult().isIsForcedUpdate()) {
                m_progressDlg = new ProgressDialog(this);
                m_progressDlg.setCancelable(false);
                m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                doNewUpdate(dataBean);//强制更新
//                } else {
//                    doNewVersionUpdate();//不强制更新
//                }


            } else {
                MyApp.needUpdaate = false;
                SpUtil.putString(this, ConStant.UPDATEPATH, "");
            }
        }
    }

//    private void doNewVersionUpdate() {
//        int verCode = Common.getVerCode(getApplicationContext());
//        String verName = Common.getVerName(getApplicationContext());
//
//        String str = "当前版本：V" + verName + " ,发现新版本：V" + versionBean.getResult().getVersion() +
//                " ,是否更新？";
//        Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新").setMessage(str)
//                // 设置内容
//                .setPositiveButton("更新",// 设置确定按钮
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog,
//                                                int which) {
//                                m_progressDlg.setTitle("正在下载");
//                                m_progressDlg.setMessage("请稍候...");
//                                url = versionBean.getResult().getDownloadUri();
//                                android.util.Log.i("url", url);
//                                downFile(url);  //开始下载
//                            }
//                        })
//                .setNegativeButton("暂不更新",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog,
//                                                int whichButton) {
//                                // 点击"取消"按钮之后退出程序
//                                dialog.dismiss();
//                            }
//                        }).create();// 创建
//        // 显示对话框
//        dialog.show();
//    }

    private void doNewUpdate(UpdateData.DataBean dataBean) {
        int verCode = CommonUtil.getVersionCode(getApplicationContext());
        String verName = CommonUtil.getVersionName(getApplicationContext());
        String str = getString(R.string.profile_hint_item23, verName, dataBean.getVersion()
                , (!TextUtils.isEmpty(dataBean.getVersiondes()) ? dataBean.getVersiondes() : getString(R.string.profile_hint_item19)));
        CommonUtil.showUpdataDialog(this, str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog1,
                                int which) {

                if (!isGrantExternalRW(MainActivity.this)) {
                    return;
                } else {
                    m_progressDlg.setTitle(getString(R.string.profile_hint_item21));
                    m_progressDlg.setMessage(getString(R.string.profile_hint_item22));
                    m_progressDlg.setMax((int) 100);//设置进度条的最大值
                    downloadApk();
                }
            }
        }, new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog1) {

//                dialog.show();

            }
        });
    }

    private Handler m_mainHandler;

    /**
     * 告诉HANDER已经下载完成了，可以安装了
     */
    private void down() {
        m_mainHandler = new Handler();
        m_mainHandler.post(new Runnable() {
            public void run() {
                m_progressDlg.cancel();
                update();
            }
        });
    }

    /**
     * 安装程序
     */
    void update() {
//        SPUtils.putBoolean(this, Constant.ISFIRST, false);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(SpUtil.getString(this, ConStant.UPDATEPATH, ""));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileProvider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
        finish();
//        System.exit(0);
    }


    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
//            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

    }

    @Override
    public void ShowProgress() {

    }

    @Override
    public void hideProgress() {

    }


    /**
     * 返回版本号
     *
     * @return 非-1 则代表获取成功
     */
    private int getVersionCode() {
        // 包管理者对象packageManager
        PackageManager pm = getPackageManager();
        // 从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            // 获取版本名称
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取储存权限
     *
     * @param activity
     * @return
     */

    public static boolean isGrantExternalRW(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

            return false;
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            LogUtil.e("Permission: " + permissions[0] + "was " + grantResults[0]);
            m_progressDlg.setTitle(getString(R.string.profile_hint_item21));
            m_progressDlg.setMessage(getString(R.string.profile_hint_item22));
            m_progressDlg.setMax((int) 100);//设置进度条的最大值
            downloadApk();
        } else {
            doNewUpdate(dataBean);//强制更新
//            dialog.show();
        }
    }


    protected void downloadApk() {
        if (m_progressDlg != null) {
            m_progressDlg.show();
        }
        LogUtil.e("downloadApk.updateApkUrl=" + updateApkUrl);
        ADBInstallApk.getInstance().downloadApk(MainActivity.this, updateApkUrl, apkname + ".apk", new ADBInstallApk.adbInstallAPKListener() {
            @Override
            public void onDownloadSuccess(String path) {
                SpUtil.putString(MainActivity.this, ConStant.UPDATEPATH, path);
                down();
//        hideProgressDialog();
//        showUpdateAlertDialog(this, "新版本安装", "有新版本可以安装啦!", "同意", "取消", this);
            }

            @Override
            public void onDownloading(int progressm) {
                LogUtil.d("99" + "progressm=" + progressm + "");
                if (progressm == 0)
                    return;

                m_progressDlg.setProgress(progressm);
            }
        });
    }

    @Override
    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
        switch (which) {
            case NEUTRAL:

                break;
            case NEGATIVE:

                hideUpdateAlertDialog();
                break;
            case POSITIVE:
                if (dialog.getTitleView().getText().toString().equals(getString(R.string.profile_hint_item18))) {
                    downloadApk();
                    progressDialog = showProgressDialog(this, "", new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        }
                    });
                    if (progressDialog != null) {
                        progressDialog.setProgress(0);
                    }

                } else if (dialog.getTitleView().getText().toString().equals(getString(R.string.profile_hint_item24))) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    File file = new File(SpUtil.getString(this, ConStant.UPDATEPATH, ""));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri contentUri = FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileProvider", file);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    }
                    startActivity(intent);
                }
                break;
        }

    }

    @Override
    public void meFragToWalletFrag(int walletType) {
        alphaIndicator.setTabCurrenItem(0);
        mainActyLisenter.mainActySetWallet(walletType);
    }

    ToBindDialogFragment dialogFragment;

    @Override
    public void toBind(boolean isPayPwd, boolean bindEmail, boolean bindMnemonic, boolean bindGoogleCode) {
//        DialogUtils.toBind(this,getSupportFragmentManager(),isPayPwd,bindEmail,bindMnemonic,bindGoogleCode);


//        if (bindEmail && bindMnemonic && !isPayPwd) {
//            if (EmptyUtils.isNotEmpty(dialogFragment)) {
//                dialogFragment.dismissParent();
//            }
//            UserWalletData.DataBean.UserMsgBean userMsgBean = new UserWalletData.DataBean.UserMsgBean();
//            userMsgBean.setTitle(getString(R.string.common_warmprompt));
//            userMsgBean.setContent(getString(R.string.dialog_hint_tosetpaypsw_worm));
//
//            ToSetPayPswDialogFragment dialogFragment = new ToSetPayPswDialogFragment();
//            dialogFragment.setDialogBean(new BaseDialogBean("eggroal", userMsgBean));
//
//            dialogFragment.setListener(new ToSetPayPswDialogFragment.ClickListener() {
//                @Override
//                public void Listener(String name, int potion) {
////                showToast(getString(R.string.paypasw_hint_setpaypsw));
//                    Intent intent = new Intent(MainActivity.this, PayPwdActivity.class);
//                    intent.putExtra("PayPwdActivityType", PayPwdActivity.PAYPSW_SET);
//                    startActivity(intent);
//                }
//            });
//
//            dialogFragment.show(getSupportFragmentManager(), "NoticeDialogFragment");
//            getFragmentManager().executePendingTransactions();
//        } else if (!bindEmail || !bindMnemonic || !bindGoogleCode) {
//
//            UserWalletData.DataBean.UserMsgBean userMsgBean = new UserWalletData.DataBean.UserMsgBean();
//            userMsgBean.setTitle(getString(R.string.common_warmprompt));
//            String content = getString(!bindEmail ? R.string.dialog_hint_tobindmai_worm : !bindMnemonic ? R.string.dialog_hint_tobindmonic_worm :
//                    R.string.dialog_hint_tobindgooglecode_worm);
//            userMsgBean.setContent(content);
//
//            int type = !bindEmail ? BINDTYPE_MAIL : !bindMnemonic ? BINDTYPE_MONIC : BINDTYPE_GOOGLECODE;
//
//            if (EmptyUtils.isNotEmpty(dialogFragment)) {
//                dialogFragment.dismissParent();
//            }
//            dialogFragment = new ToBindDialogFragment();
//            dialogFragment.setDialogBean(new BaseDialogBean(type, userMsgBean));
//
//            dialogFragment.setListener(new ToBindDialogFragment.ClickListener() {
//                @Override
//                public void Listener(String name, int type) {
//                    if (type == BINDTYPE_MAIL || type == BINDTYPE_MONIC) {
//                        //强制性绑定邮箱  绑定邮箱需要查看是否设置了支付密码，设置了支付密码需要检测支付密码
//                        Intent intent = new Intent(MainActivity.this, BindEmaiActivity.class);
//                        intent.putExtra("BINDMAI_type", BINDMAI_bind);
//                        startActivity(intent);
//                    } else if (type == BINDTYPE_GOOGLECODE) {
//                        //非强制性绑定谷歌验证码
//                        Intent intent = new Intent(MainActivity.this, BindGoogleCodeActivity.class);
//                        intent.putExtra("BINDGOOGLECODE_type", BINDGOOGLECODE_BINd);
//                        startActivity(intent);
//                    }
//
////                    else if (type ==BINDTYPE_MONIC) {
////                        //强制性绑定助记词
////                        //生成助记词
////                        startActivity(MnemonicActivity.class);
////                    }
////        else if (bindGoogleCode) {
////            //非强制性绑定谷歌验证码
////            Intent intent = new Intent(MainActivity.this, BindGoogleCodeActivity.class);
////            intent.putExtra("BINDGOOGLECODE_type", BINDGOOGLECODE_UNBINd);
////            startActivity(intent);
////        }
//
////                    else if (bindEmail) {
////                        Intent intent = new Intent(MainActivity.this, BindEmaiActivity.class);
////                        intent.putExtra("BINDMAI_type", BINDMAI_up);
////                        startActivity(intent);
////                    }
//                }
//            });
//            dialogFragment.show(getSupportFragmentManager(), "ToBindDialogFragment");
//            getFragmentManager().executePendingTransactions();
//        }

    }


    /***  弹出提示公告  ***/
    public void showToBindDialog() {

    }

    @Override
    public void getCode(RegisterData registerData) {

    }

    @Override
    public void getMonic(GoogleAuthKeyData googleAuthKeyData) {

    }

    @Override
    public void unbindGoogleSecretKey(GoogleAuthKeyData googleAuthKeyData) {

    }


    private class MainViewPageAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {

        List<Fragment> fragments = new ArrayList<>();
        WalletPageFrag walletPageFrag1;
        HangQingPageFrag hangQingPageFrag;
        HangQingPageFrag findMorePageFrag;

        public MainViewPageAdapter(FragmentManager fm, MePageFrag.MeFragLisenter lisenter) {
            super(fm);
            walletPageFrag1 = WalletPageFrag.newInstance();
            hangQingPageFrag = HangQingPageFrag.newInstance(HangQingPageFrag.HANGQING);
            fragments.add(walletPageFrag1);
            fragments.add(hangQingPageFrag);
//            fragments.add(new Fragment());
//            fragments.add(ApplicationPageFrag.newInstance());
            fragments.add(FortunePageFrag.newInstance());

//            if (SpUtil.getString(MyApp.context, ConStant.LANGAUE, "" + LanguageUtils.CHINESE_SIMPLE)
//                    .equalsIgnoreCase(LanguageUtils.CHINESE_SIMPLE)) {
//                fragments.add(FindMorePageFrag.newInstance());
//            } else {
//                findMorePageFrag = HangQingPageFrag.newInstance(HangQingPageFrag.FAXIAN);
//                fragments.add(findMorePageFrag);
//            }
            fragments.add(FindMorePageFrag.newInstance());
            fragments.add(MePageFrag.newInstance(lisenter));
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }

        public MainActyLisenter getMainActyLisenter() {

            return walletPageFrag1;
        }

        public MainActyHangQingLisenter getMainActyHangQingLisenter() {

            return hangQingPageFrag;
        }

        public MainActyHangQingLisenter getMainActyFaXianLisenter() {

            return findMorePageFrag;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        boolean flag = false;
        if (tabId == 1) {//行情需要处理
//            showToast("行情需要处理");
            flag = mainActyHangQingLisenter.mainActyHangQing(MainActivity.this, keyCode, event);
            if (flag) {
                return flag;
            }
        }

        boolean flag2 = false;
        if (mainActyFanXianLisenter != null && tabId == 3 && !
                SpUtil.getString(MyApp.context, ConStant.LANGAUE, "" + LanguageUtils.CHINESE_SIMPLE)
                        .equalsIgnoreCase(LanguageUtils.CHINESE_SIMPLE)) {//非中文版 发现网页需要处理
//            showToast("行情需要处理");
            flag2 = mainActyFanXianLisenter.mainActyHangQing(MainActivity.this, keyCode, event);
            if (flag2) {
                return flag2;
            }
        }

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    Long mExitTime = 0L;

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 3000) {
            Toast.makeText(MainActivity.this, getString(R.string.profile_hint_item12) + getString(R.string.app_name), Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    public interface MainActyLisenter {
        void mainActySetWallet(int walletType);
    }

    public interface MainActyHangQingLisenter {
        boolean mainActyHangQing(MainActivity context, int keyCode, KeyEvent event);
    }

}
